#/bin/bash

# nginx-1.20.1 Compile and install

nginx_pkg="nginx-1.20.1.tar.gz"
nginx_edition=`echo $nginx_pkg | cut -d'.' -f1-3`
nginx_install_dir="/usr/local/nginx"
nginx_user="nginx"
nginx_group="nginx"

# 检测系统，用户，yum源，wget命令
check() {
	[ ! -e /etc/redhat-release ] && cho -e "\e[1;31mERROR：仅支持redhat系列！\e[0m" && exit 1
	[ $USER != root ] && echo -e "\e[1;31mERROR：执行此脚本需root用户！\e[0m" && exit 1
	[ $(yum repolist | awk '/repolist/{print$2}' | sed 's/,//') -eq 0 ] && echo -e "\e[1;31mERROR：请检查yum源配置。\e[0m" && exit 1
	yum list installed | grep wget &> /dev/null
	test $? -ne 0 && echo -e "\e[1;31m未找到wget，正在安装wget...\e[0m" && yum -y install wget &> /dev/null
}

# 安装依赖，下载源码包
install_pre() {
	echo -e "\e[1;31m安装依赖中，勿中断脚本，请等待...\e[0m"
	if ! (yum -y install zlib zlib-devel openssl openssl-devel pcre pcre-devel gcc gcc-c++ make cmake) 1> /dev/null;then
		echo -e "\e[1;31mERROR：安装依赖包出现意外\e[0m"
		exit 2
	fi
	
	echo -e "\e[1;31m下载nginx源码包，勿中断脚本，请等待...\e[0m"
	if wget http://nginx.org/download/$nginx_pkg;then
		tar xf $nginx_pkg
		if [ ! -d $nginx_edition ];then
			echo -e "\e[1;31mERROR：未找到$nginx_edition\e[0m"
			exit 2
		fi
	else
		echo -e "\e[1;31mERROR：下载nginx源码包失败\e[0m"
		exit 2
	fi
}

install() {
	echo -e "\e[1;31m编译安装nginx中，勿中断脚本，请等待...\e[0m"
	useradd -r -s /sbin/nologin $nginx_user
	echo -e "\e[1;34mnginx configure...\e[0m"
	cd $nginx_edition
	if ./configure --prefix=$nginx_install_dir --user=$nginx_user --group=$nginx_group --with-http_stub_status_module --with-http_ssl_module 1> /dev/null;then
		echo -e "\e[1;34mnginx make...\e[0m"
		if make 1> /dev/null;then
			echo -e "\e[1;34mnginx make install...\e[0m"
			if make install 1> /dev/null;then
				echo -e "\e[1;32mnginx安装成功\e[0m"
			else
				echo -e "\e[1;31mERROR：nginx make install失败\e[0m"
	                        exit 3
			fi
		else
			echo -e "\e[1;31mERROR：nginx make失败\e[0m"
			exit 3
		fi
	else
		echo -e "\e[1;31mERROR：nginx configure失败\e[0m"
		exit 3
	fi
}

nginx_test() {
	if $nginx_install_dir/sbin/nginx -c $nginx_install_dir/conf/nginx.conf;then
		echo -e "\e[1;32mnginx启动成功\e[0m"
		curl -I http://localhost
		cd ..
		mv -f ./nginx /etc/init.d/ &> /dev/null
		if [ $? -eq 0 ];then
			chmod a+x /etc/init.d/nginx
			chkconfig --add /etc/init.d/nginx
			chkconfig nginx on
			if [ $? -eq 0 ];then
				echo -e "\e[1;32mnginx已开机启动\e[0m"
				systemctl restart nginx.service
				echo -e "\e[1;32m可使用systemctl start|stop|reload|restart nginx.service管理nginx\e[0m"
				echo -e "\e[1;32m也可使用service nginx start|stop|reload|restart管理nginx\e[0m"
			else
				echo -e "\e[1;31m设置nginx开启启动失败，请检查启动脚本\e[0m"
			fi
		else
			echo -e "\e[1;34m安装完成，请自行编辑nginx启动管理脚本或使用绝对路径使用nginx命令。\e[0m"
		fi
	else
		echo -e "\e[1;31mnginx启动失败\e[0m"
		exit 4
	fi	
}


# Call function
echo -e "\e[1;34m此脚本为编译安装nginx脚本，安装路径为$nginx_install_dir，版本为$nginx_edition\e[0m"
read -p "是否开始安装，按y开始，输入其它退出脚本：" $confirm
if [ $confirm=='y' -o $confirm=='Y' ];then
	check
	install_pre
	install
	nginx_test
else
	exit 5
fi
